//
//  YTNetManager.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/5/4.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTNetManager.h"
#import <YYModel/YYModel.h>
#import "YTUtilityManager.h"
#import "NSString+YTExtension.h"
#import "NSDictionary+YTExtension.h"
#import <AFNetworking/AFNetworking.h>
#import <CocoaSecurity/CocoaSecurity.h>
#import <AFNetworking/AFNetworkReachabilityManager.h>
#import <AFNetworking/AFNetworkActivityIndicatorManager.h>


//#if DEBUG
//#define BASE_URL @"http://devptr.yitu8.cn"
//#else
#define BASE_URL @"http://apiv3.yitu8.cn"
//#endif

@implementation YTNetManager

+ (instancetype)manager {
    static YTNetManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[YTNetManager alloc] init];
    });
    
    return manager;
}

- (void)postWithURL:(NSString *)url
         parameters:(NSDictionary *)parameters
            success:(YTRequestSuccess)success
            failure:(YTRequestFailure)failure {
    [YTNetManager networkActivityIndicatorShow];
    NSString *router = [NSString stringWithFormat:@"/driver/%@", url];
    NSDictionary *dataDict = [self configParametersWithURL:router data:parameters];
    NSString *dataJson = [dataDict yy_modelToJSONString];
    NSData *data = [dataJson dataUsingEncoding:NSUTF8StringEncoding];
    NSString *urlString = [BASE_URL stringByAppendingString:router];
//    NSLog(@"%@", dataJson);
    
    /// 发起请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
    request.HTTPMethod = @"POST";
    request.HTTPBody = data;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    request.timeoutInterval = 30;
    [[[self configHTTPSessionManager] uploadTaskWithRequest:request fromData:data progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 成功
            if (responseObject) {
                success(responseObject);
            }
            // 失败
            if (error) {
                [self showTips:@"网络发生了错误🤖\n是不是网络君悄悄溜走了?\n请检查您的网络无误后重试"];
                [SVProgressHUD dismiss];
                failure(error);
#if DEBUG
                NSLog(@"%@", error.description);
#endif
            }
            
            [YTNetManager networkActivityIndicatorDissmis];
        });
    }] resume];
}

- (void)getWithURL:(NSString *)url
           success:(YTRequestSuccess)success
           failure:(YTRequestFailure)failure {
    [[self configHTTPSessionManager] GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

#pragma mark - 网络检测

+ (BOOL)isReachableNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachable;
}

+ (BOOL)isWiFiNetwork {
    return [AFNetworkReachabilityManager sharedManager].isReachableViaWiFi;
}

+ (BOOL)isMobileNetwork {
    return [AFNetworkReachabilityManager sharedManager].isReachableViaWWAN;
}

+ (void)networkActivityIndicatorShow {
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible = true;
    });
}

+ (void)networkActivityIndicatorDissmis {
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    });
}

#pragma mark - AFN初始化

/**
 配置AFN
 
 @return AFHTTPSessionManager
 */
- (AFHTTPSessionManager *)configHTTPSessionManager {
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableLeaves | NSJSONWritingPrettyPrinted | NSJSONReadingAllowFragments];
        manager.requestSerializer.timeoutInterval = 30;
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/javascript",@"text/html", nil];
        [AFNetworkActivityIndicatorManager sharedManager].enabled = true;
        
        // 开启HTTPs
        //    manager.securityPolicy = [self configSecurityPolicy];
    });
    
    return manager;
}


/**
 HTTPS证书加载
 
 @return AFSecurityPolicy
 */
- (AFSecurityPolicy *)configSecurityPolicy {
    // SSL验证
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    
    // 如果后台开启的是双向验证，打开这里的代码，把对应的证书放入相应的位置即可
    //    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];
    //    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    //    NSMutableSet *certSet = [NSMutableSet setWithCapacity:1];
    //    [certSet addObject:certData];
    [securityPolicy setAllowInvalidCertificates:YES];
    [securityPolicy setValidatesDomainName:NO];
    
    return securityPolicy;
}


/**
 配置请求
 
 @param data 请求数据
 @param method 请求方法
 @param url URL
 @return instancetype
 */
+ (NSMutableURLRequest *)configRequestWithData:(NSData *)data method:(NSString *)method url:(NSString *)url {
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:method URLString:url parameters:nil error:nil];
    
    req.timeoutInterval= 30;
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [req setHTTPBody:data];
    
    return req;
}

#pragma mark - cookies处理

- (void)prepareForCookies {
    // 获取cookie库
    //    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
}

#pragma mark - 公共参数部分处理V3

- (NSDictionary *)configParametersWithURL:(NSString *)url
                                     data:(NSDictionary *)data {
    // 获取action - controller - module - userid
    NSArray *array = [url componentsSeparatedByString:@"/"];
    BOOL isLogin = ([[YTUtilityManager manager] getUserID] != nil);
    
    // 参数拼接
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"action"] = array[3];
    dict[@"module"] = array[1];
    dict[@"controller"] = array[2];
    dict[@"actionTime"] = [NSString yt_getCurrentTime];
    dict[@"appId"] = @"1002";
    dict[@"requestData"] = data == nil ? @{} : data;
    if (isLogin) {
        dict[@"token"] = [[YTUtilityManager manager] getUserToken];
        dict[@"checkSum"] = [self checkSumController:array[2] action:array[3] data:data];
        dict[@"userId"] = [[YTUtilityManager manager] getUserID];
    }
    
    return dict;
}

- (NSString *)checkSumController:(NSString *)controller
                          action:(NSString *)action
                            data:(NSDictionary *)data {
    NSString *check = nil;
    NSString *actionTime = [NSString yt_getCurrentTime];
    NSString *userID = [[YTUtilityManager manager] getUserID];
    NSString *dataJSON = [data yy_modelToJSONString];
    NSString *deviceID = [[YTUtilityManager manager] getDeviceId];
    NSString *token = [[YTUtilityManager manager] getUserToken];
    check = [NSString stringWithFormat:@"client%@%@%@1002%@%@%@%@", controller, action, actionTime, userID, dataJSON, deviceID, token];
    
    return [CocoaSecurity md5:check].hex;
}

#pragma mark - private

- (void)showTips:(NSString *)tips {
    [UIAlertView bk_showAlertViewWithTitle:@"友情提示"
                                   message:tips
                         cancelButtonTitle:@"确认" otherButtonTitles:nil
                                   handler:^(UIAlertView *alertView, NSInteger buttonIndex) {}];
}

@end
